package fightplan;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;

public class LastFiles {

	private static final int RECENTS = 4;
	private static final DateFormat dateFormat = DateFormat.getDateInstance();

	private Properties properties;
	private File[] files;
	private Date[] dates;

	public LastFiles() {
		files = new File[RECENTS];
		dates = new Date[RECENTS];

		load();
	}

	public File[] getFiles() {
		return files;
	}

	public int getFileCount() {
		for (int i = 0; i < files.length; i++) {
			if (files[i] == null)
				return i;
		}
		return files.length;
	}

	public boolean isOld() {
		if (dates.length < 1)
			return true;

		Date date = new Date();
		date.setTime(date.getTime() - 7 * 24 * 3600 * 1000); // - 7 Days

		return dates[0].before(date);
	}

	public void putFile(File file) {
		if (file.equals(files[0]))
			return;

		for (int i = files.length - 2; i >= 0; i--) {
			files[i + 1] = files[i];
			dates[i + 1] = dates[i];
		}
		files[0] = file;
		dates[0] = new Date();
		save();
	}

	private void save() {
		try {
			properties = new Properties();
			for (int i = 0; i < getFileCount(); i++) {
				properties.put("file." + i, files[i].getCanonicalPath());
				properties.put("date." + i, dateFormat.format(dates[i]));
			}
			properties.save(new FileOutputStream(new File("lastFiles.txt")), "Written " + new Date());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void load() {
		try {
			properties = new Properties();

			properties.load(new FileInputStream(new File("lastFiles.txt")));
			for (int i = 0; i < RECENTS - 1; i++) {
				files[i] = new File((String) properties.get("file." + i));
				dates[i] = dateFormat.parse((String) properties.get("date." + i));
			}
		} catch (Exception e) {
			// silent
		}
	}
}
